package com.llt.music.controller;

import com.llt.music.model.Music;
import com.llt.music.model.User;
import com.llt.music.service.MusicService;
import com.llt.music.tools.Constant;
import com.llt.music.tools.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/music")
public class MusicController {

    @Resource
    private MusicService musicService;

    @Value("${music.local.path}")
    private String SAVE_PATH;

    @RequestMapping("/add")
    public Result insertMusic(String singer, @RequestParam("filename") MultipartFile file, HttpServletRequest request) {
        log.info("正在上传音乐....................");

        // 1. 判断用户是否登陆
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            log.error("未登录");
            return Result.fail("未登录");
        }

        // 2. 上传音乐（保存到服务器）
        // 获取文件的完整名称
        String fileNameAndType = file.getOriginalFilename();

        // 上传到的文件路径
        String path = SAVE_PATH + fileNameAndType;

        File dest = new File(path);

        // 上传文件
        try {
            file.transferTo(dest);
            log.info("上传到本地成功");
        } catch (IOException e) {
            log.error("服务器上传失败");
            return Result.fail("服务器上传失败");
        }

        // 3. 上传到数据库
        int ret = 0;
        if (fileNameAndType != null) {
            // 标题
            String title = fileNameAndType.substring(0, fileNameAndType.lastIndexOf("."));

            // 用户 id
            User user = (User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
            int userId = user.getId();

            // url
            String url = "/music/get?path=" + title;

            // 时间
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            String time = sf.format(new Date());

            // 判断数据库中是否已经存在
            if (musicService.query(title, singer) != null) {
                log.info("数据库中存在!!!");
                return Result.success("已经存在", fileNameAndType);
            }else {
                ret = musicService.add(title, singer, time, url, userId);
            }

        }

        if (ret == 1) {
            log.info("上传到数据库成功：{}条: {}",ret, fileNameAndType);
        }else {
            dest.delete();
            log.error("上传到数据库失败!!!");
            return Result.fail("数据库上传失败");
        }

        return Result.success("上传成功", fileNameAndType);
    }


    @RequestMapping("/get")
    public ResponseEntity<byte[]> func(String path) {
        File file = new File(SAVE_PATH + "/" + path);
        byte[] a = null;
        try {
            a = Files.readAllBytes(file.toPath());
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @RequestMapping("/delete")
    public Result deleteMusicById(String id) {
        log.info("正在删除音乐....................");
        // 检查音乐是否存在
        int iid = Integer.parseInt(id);
        Music music = musicService.queryById(iid);
        if (music == null) {
            return Result.fail("音乐不存在");
        }else {
            // 删除数据库
            int ret = musicService.deleteByid(iid);
            if (ret == 1) {
                // 删除服务器上的数据
                String fileName = music.getTitle();

                File file = new File(SAVE_PATH + fileName + ".mp3");
                log.info("要删除的文件{}", file);

                if (file.delete()) {
                    return Result.success("删除成功", fileName);
                }else {
                    return Result.fail("删除失败");
                }

            }else {
                return Result.fail("数据库删除失败");
            }
        }
    }

    @RequestMapping("/deleteSel")
    public Result deleteSel(@RequestParam("id[]") List<Integer> ids) {
        log.info("正在批量删除音乐....................");
        int deleteSum = 0;
        for (Integer i : ids) {
            Music music = musicService.queryById(i);
            if (music == null) {
                return Result.fail(i + "位置: 音乐不存在");
            }

            int ret = musicService.deleteByid(i);
            if (ret == 1) {
                // 删除服务器上的数据
                String fileName = music.getTitle();

                File file = new File(SAVE_PATH + fileName + ".mp3");
                log.info("要删除的文件{}", file);

                if (file.delete()) {
                   deleteSum += 1;
                }else {
                    return Result.fail("删除失败");
                }
            }
        }

        if (deleteSum == ids.size()) {
            return Result.success("删除成功", ids);
        }

        return Result.fail("删除失败");
    }

    @RequestMapping("/findMusic")
    public Result findMusic() {
        log.info("正在查询删除音乐....................");



    }



}
